import { getCollection } from '@/service/collection';
import { AddPermissionParams, GetPermissionParams, IPermission, UpdatePermissionParams } from '@/service/types';
import { pick, rest } from 'lodash-es';

export const permissionCollection = getCollection<IPermission>('uni-id-permissions');

const fields = ['permission_id', 'permission_name', 'comment'];

const existPermission = async (permission_id: string) => {
	try {
		const res = await permissionCollection.where({ permission_id }).getOne();
		return !!res.data;
	} catch (error) {
		throw error;
	}
};

const existPermissionById = async (id: string) => {
	try {
		const res = await permissionCollection.where({ _id: id }).getOne();
		return !!res.data;
	} catch (error) {
		throw error;
	}
};
const getAllPermission = async () => {
	try {
		const res = await permissionCollection.get();
		return res.data;
	} catch (error) {
		throw error;
	}
};

const getPermissionTreeOptions = async () => {
	try {
		const res = await permissionCollection.getTree();
		return res.data;
	} catch (error) {
		throw error;
	}
};
const getPaginationPermission = async (params: PaginationParams) => {
	try {
		const res = await permissionCollection
			.where(params.query ? params.query : {})
			.limit(params.limit)
			.skip(params.skip)
			.get({ getCount: true });
		return res;
	} catch (error) {
		throw error;
	}
};
const addPermission = async (data: AddPermissionParams) => {
	try {
		const exist = await existPermission(data.permission_id);
		if (exist) {
			throw new Error('权限标识已存在');
		}

		const pickData = pick(data, fields);

		const res = await permissionCollection.add(pickData);
		return res.id;
	} catch (error) {
		throw error;
	}
};

const updatePermission = async (data: UpdatePermissionParams) => {
	const exist = await existPermissionById(data._id);
	if (!exist) {
		throw new Error('权限标识不存在');
	}
	const pickData = pick(data, fields);
	try {
		const res = await permissionCollection
			.where({
				_id: data._id,
			})
			.update(pickData);
		return res.updated;
	} catch (error) {
		throw error;
	}
};

const deletePermission = async (id: string) => {
	try {
		const res = await permissionCollection.where({ _id: id }).remove();
		return res.deleted;
	} catch (error) {
		throw error;
	}
};
export const permission = {
	getAllPermission,
	addPermission,
	updatePermission,
	getPaginationPermission,
	deletePermission,
	getPermissionTreeOptions,
};
